package com.big.common.feign.config;

import feign.Logger;
import feign.RequestInterceptor;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

/**
 * <p>
 * Feign客户端全局配置类，提供日志级别、请求拦截器等配置
 * </p>
 *
 * @author 山归岿
 * @create 2025-06-15-19:42
 */
@Configuration
public class FeignConfig {

    /**
     * Feign日志级别配置
     * NONE: 不记录任何日志（默认）
     * BASIC: 仅记录请求方法、URL以及响应状态码和执行时间
     * HEADERS: 记录BASIC级别的基础上，记录请求和响应的header
     * FULL: 记录所有请求和响应的明细，包括头信息、请求体、元数据
     */
    @Bean
    public Logger.Level feignLoggerLevel() {
        return Logger.Level.BASIC;
    }

    /**
     * 请求拦截器
     * 用于在发送请求前添加通用的请求头信息
     */
    @Bean
    public RequestInterceptor requestInterceptor() {
        return template -> {
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();

                // 传递请求头信息
                String authorization = request.getHeader("Authorization");
                if (authorization != null) {
                    template.header("Authorization", authorization);
                }

                String traceId = request.getHeader("X-Trace-Id");
                if (traceId != null) {
                    template.header("X-Trace-Id", traceId);
                }
            }
        };
    }
}